package com.wgcloud.httpClient;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class HttpClientUtil {

    @Autowired
    private CloseableHttpClient httpClient;

    // 发送GET请求并返回JSONObject
    public JSONObject sendGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity);
            return new JSONObject(responseString);
        } catch (IOException e) {
            log.error("发送GET请求失败: ", e);
            return null;
        }
    }

    // 发送POST请求并返回JSONObject
    public JSONObject sendPost(String url, String jsonPayload) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(jsonPayload, StandardCharsets.UTF_8));

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity);
            return new JSONObject(responseString);
        } catch (IOException e) {
            log.error("发送POST请求失败: ", e);
            return null;
        }
    }
}